<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 java 的 String 类可以说是日常中使用的最多的类，但是大多数时候都只是简单的拼接或者调用 API，只知其然不知其所以然。为了改变这个情况，我决定结合网上的资料，参考源码，深入一点去了解 String 这个熟悉的陌生人。 要第一时间了解一个类，没有什么比官方的文档更直观的了：  String类表示字符串。Java程序中的所有字符串文本（如“abc”）都作为此类的实例实现。 字符串是常">
<meta property="og:type" content="article">
<meta property="og:title" content="String类源码分析">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/08/11/java/String%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 java 的 String 类可以说是日常中使用的最多的类，但是大多数时候都只是简单的拼接或者调用 API，只知其然不知其所以然。为了改变这个情况，我决定结合网上的资料，参考源码，深入一点去了解 String 这个熟悉的陌生人。 要第一时间了解一个类，没有什么比官方的文档更直观的了：  String类表示字符串。Java程序中的所有字符串文本（如“abc”）都作为此类的实例实现。 字符串是常">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/%E5%AD%97%E9%9D%A2%E9%87%8F%E5%BD%A2%E5%BC%8F%E5%88%9B%E5%BB%BAString.png">
<meta property="og:image" content="http://img.xiajibagao.top/new%E5%85%B3%E9%94%AE%E5%AD%97%E5%88%9B%E5%BB%BAString.png">
<meta property="og:image" content="http://img.xiajibagao.top/%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C%E5%90%8E%E5%A0%86%E5%92%8C%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E7%9A%84String%E5%AF%B9%E8%B1%A1.png">
<meta property="article:published_time" content="2020-08-10T16:00:00.000Z">
<meta property="article:modified_time" content="2021-02-16T09:42:41.555Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/%E5%AD%97%E9%9D%A2%E9%87%8F%E5%BD%A2%E5%BC%8F%E5%88%9B%E5%BB%BAString.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/08/11/java/String类源码分析/"/>





  <title>String类源码分析 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/08/11/java/String%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">String类源码分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-08-11T00:00:00+08:00">
                2020-08-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.1k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>java 的 String 类可以说是日常中使用的最多的类，但是大多数时候都只是简单的拼接或者调用 API，只知其然不知其所以然。为了改变这个情况，我决定结合网上的资料，参考源码，深入一点去了解 String 这个熟悉的陌生人。</p>
<p>要第一时间了解一个类，没有什么比官方的文档更直观的了：</p>
<blockquote>
<p>String类表示字符串。Java程序中的所有字符串文本（如“abc”）都作为此类的实例实现。</p>
<p><strong>字符串是常量；它们的值在创建后不能更改</strong>。字符串缓冲区支持可变字符串。<strong>因为字符串对象是不可变的，所以可以共享它们</strong>。</p>
<p><strong>Java语言提供了对字符串连接运算符（+）以及将其他对象转换为字符串的特殊支持。字符串连接是通过<code>StringBuilder</code>（或<code>StringBuffer</code>）类及其<code>append</code>方法实现的。字符串转换是通过<code>toString</code>方法实现的</strong></p>
<p>… …</p>
</blockquote>
<p>根据文档，对于String类，我们关注三个问题：</p>
<ul>
<li>String对象的不可变性（为什么是不可变的，这么设计的必要性）</li>
<li>String对象的创建方式（两种创建方式，字符串常量池）</li>
<li>String对象的拼接（StringBuffer，StringBuilder，加号拼接的本质）</li>
</ul>
<h2 id="一-string对象的不可变性">一、String对象的不可变性</h2>
<h3 id="1string为什么是不可变的">1.String为什么是不可变的</h3>
<p>文档中提到：</p>
<blockquote>
<p>字符串是常量；它们的值在创建后不能更改。</p>
</blockquote>
<p>对于这段话我们结合源码来看;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">String</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span>, <span class="title">Comparable</span>&lt;<span class="title">String</span>&gt;, <span class="title">CharSequence</span> </span>&#123;</span><br><span class="line">    <span class="comment">/** The value is used for character storage. */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">char</span> value[];</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** Cache the hash code for the string */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> hash; <span class="comment">// Default to 0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看到，String类字符其实就是char数组对象的二次封装，存储变量<code>value[]</code>是被final修饰的，所以一个String对象创建以后是无法被改变值的，这点跟包装类是一样的。</p>
<p>我们常见的写法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String s = <span class="string">&quot;AAA&quot;</span>;</span><br><span class="line">s = <span class="string">&quot;BBB&quot;</span>;</span><br></pre></td></tr></table></figure>
<p>实际上创建了两个String对象，我们使用 = 只是把s指从AAA的内存地址指向了BBB的内存地址。</p>
<p>我们再看看熟悉的<code>substring()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">substring</span><span class="params">(<span class="keyword">int</span> beginIndex, <span class="keyword">int</span> endIndex)</span> </span>&#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="keyword">return</span> ((beginIndex == <span class="number">0</span>) &amp;&amp; (endIndex == value.length)) ? <span class="keyword">this</span></span><br><span class="line">        : <span class="keyword">new</span> String(value, beginIndex, subLen);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看出，在最后也是返回了一个新的String对象，同理，<code>toLowerCase()</code>,<code>trim()</code>等返回字符串的方法也都是在最后返回了一个新对象。</p>
<h3 id="2string不可变的必要性">2.String不可变的必要性</h3>
<p>String之所以被设计为不可变的，目的是为了<strong>效率和安全性</strong>：</p>
<ul>
<li>效率：
<ol>
<li>String不可变是字符串常量池实现的必要条件，通过常量池可以避免了过多的创建String对象，节省堆空间。</li>
<li>String的包含了自身的HashCode，不可变保证了对象HashCode的唯一性，避免了反复计算。</li>
</ol>
</li>
<li>安全性：
<ol>
<li>String被许多Java类用来当参数，如果字符串可变，那么会引起各种严重错误和安全漏洞。</li>
<li>再者String作为核心类，很多的内部方法的实现都是本地调用的，即调用操作系统本地API，其和操作系统交流频繁，假如这个类被继承重写的话，难免会是操作系统造成巨大的隐患。</li>
<li>最后字符串的不可变性使得同一字符串实例被多个线程共享，所以保障了多线程的安全性。而且类加载器要用到字符串，不可变性提供了安全性，以便正确的类被加载。</li>
</ol>
</li>
</ul>
<h2 id="二-字符串常量池">二、字符串常量池</h2>
<h3 id="1作用">1.作用</h3>
<p>文档中有提到：</p>
<blockquote>
<p>因为字符串对象是不可变的，所以可以共享它们</p>
</blockquote>
<p>字符串常量池是一块用于记录字符串常量的特殊区域（具体可以参考我在关于<a target="_blank" rel="noopener" href="https://www.cnblogs.com/Createsequence/p/13447923.html">jvm内存结构的文章</a>），JDK8之前字符串常量池在方法区的运行时常量池中，JDK8之后分离到了堆中。“共享”操作就依赖于字符串常量池。</p>
<p>我们知道String是一个对象，而<code>value[]</code>是一个不可变值，所以当我们日常中使用String的时候就会频繁的创建新的String对象。JVM为了提高性能减少内存开销，在通过类似<code>String S = “aaa”</code>这样的操作的时候，<strong>JVM会先检查常量池是否是存在相同的字符串，如果已存在就直接返回字符串实例地址，否则就会先实例一个String对象放到池中，再返回地址</strong>。</p>
<p>举个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="string">&quot;aaa&quot;</span>;  </span><br><span class="line">String s2 = <span class="string">&quot;aaa&quot;</span>; </span><br><span class="line">System.out.print(s1 == s2);   <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>我们知道“==”比较对象的时候比较的是内存地址是否相等，当s1创建的时候，一个“aaa”String对象被创建并放入池中，s1指向的是该对象地址；当第二个s2赋值的时候，JVM从常量池中找到了值为“aaa”的字符串对象，于是跳过了创建过程，直接将s1指向的对象地址也赋给了s2.</p>
<h3 id="2入池方法intern">2.入池方法<code>intern()</code></h3>
<p>这里要提一下String对象的手动入池方法 <code>intern()</code>。</p>
<p>这个方法的注释是这样的：</p>
<blockquote>
<p>最初为空的字符串池由String类私有维护。</p>
<p>调用intern方法时，如果池已经包含等于<code>equal()</code>方法确定的此String对象的字符串，则返回池中的字符串。否则，将此String对象添加到池中，并返回对此String对象的引用。</p>
</blockquote>
<p>举个例子说明作用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="string">&quot;aabb&quot;</span>;</span><br><span class="line">String s2 = <span class="keyword">new</span> String(<span class="string">&quot;aabb&quot;</span>);</span><br><span class="line">System.out.println(s1 == s2); <span class="comment">//false</span></span><br><span class="line">System.out.println(s1 == s2.intern()); <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>最开始s1创建了“aabb”对象A，并且加入了字符串常量池，接着s2创建了新的&quot;aabb&quot;对象B，这个对象在堆中并且独立于常量池，此时s1指向常量池中的A，s2指向常量池外的B，所以==返回是false。</p>
<p>我们使用<code>intern()</code>方法手动入池，字符串常量池中已经有了值等于“aabb”的对象A，于是直接返回了对象A的地址，此时s1和s2指向的都是内存中的对象A，所以==返回了true。</p>
<h2 id="三-string对象的创建方式">三、String对象的创建方式</h2>
<p>从上文我们知道String对象的创建和字符串常量池是密切相关的，而创建一个新String对象有两种方式：</p>
<ul>
<li>使用字面值形式创建。类似 <code>String s = &quot;aaa&quot;</code></li>
<li>使用new关键字创建。类似 <code>String s = new String(&quot;aaa&quot;)</code></li>
</ul>
<h3 id="1使用字面值形式创建">1.使用字面值形式创建</h3>
<p><img src="http://img.xiajibagao.top/%E5%AD%97%E9%9D%A2%E9%87%8F%E5%BD%A2%E5%BC%8F%E5%88%9B%E5%BB%BAString.png" alt="字面值形式创建String"></p>
<p><strong>当使用字面值创建String对象的时候，会根据该字符串是否已存在于字符串常量池里来决定是否创建新的String对象。</strong></p>
<p>当我们使用类似<code>String s = &quot;a&quot;</code>这样的代码创建字符串常量的时候，JVM会先检查“a”这个字符串是否在常量池中：</p>
<ul>
<li>
<p><strong>如果存在，就直接将此String对象地址赋给引用s（引用s是个成员变量，它在虚拟机栈中）</strong>；</p>
</li>
<li>
<p><strong>如果不存在，就会先在堆中创建一个String对象，然后将对象移入字符串常量池，最后将地址赋给s</strong>。</p>
</li>
</ul>
<h3 id="2使用new关键字创建">2.使用new关键字创建</h3>
<p><img src="http://img.xiajibagao.top/new%E5%85%B3%E9%94%AE%E5%AD%97%E5%88%9B%E5%BB%BAString.png" alt="new关键字创建String"></p>
<p><strong>当使用String关键字创建String对象的时候，无论字符串常量池中是否有同值对象，都会创建一个新实例。</strong></p>
<p>看看new调用的的构造函数的注释：</p>
<blockquote>
<p>初始化新创建的字符串对象，使其表示与参数相同的字符序列；换句话说，<strong>新创建的字符串是参数字符串的副本</strong>。除非需要original的显式副本，否则没有必要使用此构造函数，因为字符串是不可变的。</p>
</blockquote>
<p>当我们使用new关键字创建String对象时，和字面值形式创建一样，JVM会检查字符串常量池是否存在同值对象：</p>
<ul>
<li><strong>如果存在，则就在堆中创建一个对象，然后返回该堆中对象的地址</strong>；</li>
<li><strong>否则就先在字符串常量池中创建一个String对象，然后再在堆中创建一个一模一样的对象，然后返回堆中对象的地址</strong>。</li>
</ul>
<p>也就是说，使用字面值创建后产生的对象只会有一个，但是用new创建对象后产生的对象可能会有两个（只有堆中一个，或者堆中一个和常量池中一个）。</p>
<p>我们举个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="string">&quot;aabb&quot;</span>;</span><br><span class="line">String s2 = <span class="keyword">new</span> String(<span class="string">&quot;aabb&quot;</span>);</span><br><span class="line">String s3 = <span class="string">&quot;aa&quot;</span> + <span class="keyword">new</span> String(<span class="string">&quot;bb&quot;</span>);</span><br><span class="line">String s4 = <span class="keyword">new</span> String(<span class="string">&quot;aa&quot;</span>) + <span class="keyword">new</span> String(<span class="string">&quot;bb&quot;</span>);</span><br><span class="line">System.out.println(s1 == s2); <span class="comment">//false</span></span><br><span class="line">System.out.println(s1 == s3); <span class="comment">//false</span></span><br><span class="line">System.out.println(s1 == s4); <span class="comment">//false</span></span><br><span class="line"></span><br><span class="line">System.out.println(s2 == s3); <span class="comment">//false</span></span><br><span class="line">System.out.println(s2 == s4); <span class="comment">//false</span></span><br><span class="line"></span><br><span class="line">System.out.println(s3 == s4); <span class="comment">//false</span></span><br></pre></td></tr></table></figure>
<p>我们可以看到，四个String对象是都是相互独立的。</p>
<p>实际上，执行完以后对象在内存中的情况是这样的：</p>
<p><img src="http://img.xiajibagao.top/%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C%E5%90%8E%E5%A0%86%E5%92%8C%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E7%9A%84String%E5%AF%B9%E8%B1%A1.png" alt="代码执行后堆和常量池中的String对象"></p>
<h3 id="3小结">3.小结</h3>
<ul>
<li>使用new或者字面值形式创建String时都会根据常量池是否存在同值对象而决定是否在常量池中创建对象</li>
<li>使用字面值创建的String，引用直接指向常量池中的对象</li>
<li>使用new创建的String，还会在堆中常量池外再创建一个对象，引用指向常量池外的对象</li>
</ul>
<h2 id="四-string的拼接">四、String的拼接</h2>
<p>我们知道，String经常会用拼接操作，而这依赖于StringBuilder类。实际上，<strong>字符串类不止有String，还有StringBuilder和StringBuffer</strong>。</p>
<p>简单的来说，StringBuilder和StringBuffer与String的主要区别在于后两者是<strong>可变的字符序列</strong>，每次改变都是针对对象本身，而不是像String那样直接创建新的对象，然后再改变引用。</p>
<h3 id="1stringbuilder">1.StringBuilder</h3>
<p>我们先看看它的注释是怎么介绍的：</p>
<blockquote>
<p><strong>可变的字符序列</strong>。</p>
<p><strong>此类提供与StringBuffer兼容的API，但不保证同步</strong>。</p>
<p>此类设计为在单线程正在使用StringBuilder的地方来代替StringBuffer。在可能的情况下，建议优先使用此类而不是StringBuffer，因为在大多数实现中它会更快。</p>
<p>StringBuilder上的主要操作是<code>append()</code>和<code>insert()</code>方法，它们会被重载以接受任何类型的数据。每个有效地将给定的基准转换为字符串，然后将该字符串的字符追加或插入到字符串生成器中。 a<strong>ppend方法始终将这些字符添加到生成器的末尾。 insert方法在指定点添加字符</strong>。</p>
<p>例如:</p>
<p>如果z指向当前内容为“ start”的字符串生成器对象，则方法调用z.append（“ le”）会使字符串生成器包含“ startle”，而z.insert（4，“ le”）将更改字符串生成器以包含“ starlet”。</p>
<p>通常，如果sb引用StringBuilder的实例，则sb.append（x）与sb.insert（sb.length（），x）具有相同的效果。每个字符串生成器都有能力。只要字符串构建器中包含的字符序列的长度不超过容量，就不必分配新的内部缓冲区。如果内部缓冲区溢出，则会自动变大。</p>
<p>StringBuilder实例不能安全地用于多个线程。如果需要这样的同步，则建议使用StringBuffer。除非另有说明，否则将null参数传递给此类中的构造函数或方法将导致引发NullPointerException。</p>
</blockquote>
<p>我们知道这个类的主要作用在于能够动态的扩展（<code>append()</code>）和改变字符串对象（<code>insert()</code>）的值。</p>
<p>我们对比一下String和StringBuilder：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//String</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">String</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span>, <span class="title">Comparable</span>&lt;<span class="title">String</span>&gt;, <span class="title">CharSequence</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//StringBuilder</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">StringBuilder</span> <span class="keyword">extends</span> <span class="title">AbstractStringBuilder</span></span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span>, <span class="title">CharSequence</span></span>&#123;&#125;</span><br></pre></td></tr></table></figure>
<p>不难看出，两者的区别在于String实现了Comparable接口而StringBulier继承了抽象类AbstractStringBuilder。后者的扩展性就来自于AbstractStringBuilder。</p>
<p>AbstractStringBuilder中和String一样采用一个<strong>char数组</strong>来保存字符串值，但是这个char数组是未经final修饰，是可变的。</p>
<p>char数组有一个初始大小，跟集合容器类似，当append的字符串长度超过当前char数组容量时，则对char数组进行动态扩展，即重新申请一段更大的内存空间，然后将当前char数组拷贝到新的位置；反之就会适当缩容。</p>
<p>一般是新数组长度默认为：<code>(旧数组长度+新增字符长度) * 2 + 2</code>。(不太准确，想要了解更多的同学可以参考AbstractStringBuilder类源码中的<code>newCapacity()</code>方法)</p>
<h3 id="2加号拼接与append方法拼接">2.加号拼接与append方法拼接</h3>
<p>我们平时一般都直接对String使用加号拼接，实际上这仍然还是依赖于StringBuilder的<code>append()</code>方法。</p>
<p>举个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s = <span class="string">&quot;&quot;</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    s += <span class="string">&quot;a&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这写法实际上编译以后会变成类似这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s = <span class="string">&quot;&quot;</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    s = (<span class="keyword">new</span> StringBuilder(String.valueOf(s))).append(<span class="string">&quot;a&quot;</span>).toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看见<strong>每一次循环都会生成一个新的StringBuilder对象，这样无疑是很低效的</strong>，也是为什么网上很多文章会说循环中拼接字符串不要使用String而是StringBuilder的原因。因为如果我们自己写就可以写成这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">StringBuilder s = <span class="keyword">new</span> StringBuilder();</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    s.append(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>明显比编译器转换后的写法要高效。</p>
<p>理解了加号拼接的原理，我们也就知道了为什么字符串对象使用加号凭借==返回的是false：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="string">&quot;abcd&quot;</span>;</span><br><span class="line">String s2 = <span class="string">&quot;ab&quot;</span>;</span><br><span class="line">String s3 = <span class="string">&quot;cd&quot;</span>;</span><br><span class="line">String s4 = s1 + s2;</span><br><span class="line">String s5 = <span class="string">&quot;ab&quot;</span> + s3;</span><br><span class="line">System.out.println(s1 == s4); <span class="comment">//false</span></span><br><span class="line">System.out.println(s1 == s5); <span class="comment">//false</span></span><br></pre></td></tr></table></figure>
<p>分析一下上面的过程，<strong>无论 <code>s1 + s2</code>还是 <code>&quot;ab&quot; + s3</code>实际上都调用了StringBuilder在字符串常量池外创建了一个新的对象</strong>，所以==判断返回了false。</p>
<p>值得一提的是，如果我们遇到了“常量+字面值”的组合，是可以看成单纯的字面值：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="string">&quot;abcd&quot;</span>;</span><br><span class="line"><span class="keyword">final</span> String s3 = <span class="string">&quot;cd&quot;</span>;</span><br><span class="line">String s5 = <span class="string">&quot;ab&quot;</span> + s3;</span><br><span class="line">System.out.println(s1 == s5); <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>总结一下就是：</p>
<ul>
<li><strong>对于“常量+字面值”的组合，可以等价于纯字面值创建对象</strong></li>
<li><strong>对于包含字符串对象引用的写法，由于会调用StringBuilder类的toString方法生成新对象，所以等价于new的方式创建对象</strong></li>
</ul>
<h3 id="3stringbuffer">3.StringBuffer</h3>
<p>同样看看它的javaDoc，与StringBuilder基本相同的内容我们跳过：</p>
<blockquote>
<p><strong>线程安全的可变字符序列</strong>。StringBuffer类似于字符串，但是可以修改。</p>
<p>对于**。字符串缓冲区可安全用于多个线程。这些方法在必要时进行同步，以使任何特定实例上的所有操作都表现为好像以某种串行顺序发生，该顺序与所涉及的每个单独线程进行的方法调用的顺序一致。</p>
<p>… …</p>
<p>请注意，虽然StringBuffer被设计为可以安全地从多个线程中并发使用，但是如果将构造函数或append或insert操作传递给在线程之间共享的源序列，则调用代码必须确保该操作具有一致且不变的视图操作期间源序列的长度。这可以通过调用方在操作调用期间保持锁定，使用不可变的源序列或不跨线程共享源序列来满足。</p>
<p>… …</p>
<p>**从JDK 5版本开始，该类已经添加了一个等效类StringBuilder，该类旨在供单线程使用。**通常应优先使用StringBuilder类，因为它支持所有相同的操作，但它更快，因为它不执行同步，因此它比所有此类都优先使用。</p>
</blockquote>
<p>可以知道，StringBuilder是与JDK5之后添加的StringBuffer是“等效类”，两个类功能基本一致，唯一的区别在于<strong>StringBuffer是线程安全的</strong>。</p>
<p>我们查看源码，可以看到<strong>StringBuffer实现线程安全的方式是为成员方法添加<code>synchronized</code>关键字进行修饰</strong>，比如<code>append()</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> StringBuffer <span class="title">append</span><span class="params">(Object obj)</span> </span>&#123;</span><br><span class="line">    toStringCache = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">super</span>.append(String.valueOf(obj));</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>事实上，StringBuffer几乎所有的方法都加了<code>synchronized</code>。这也就不难理解为什么一般情况下StringBuffer效率不如StringBuilder了，因为StringBuffer的所有方法都加了锁。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/10/jvm/JVM%E5%88%9D%E6%8E%A2%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6/" rel="next" title="JVM初探（二）：垃圾回收机制">
                <i class="fa fa-chevron-left"></i> JVM初探（二）：垃圾回收机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/08/11/jvm/JVM%E5%88%9D%E6%8E%A2%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9A%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/" rel="prev" title="JVM初探（三）：类加载机制">
                JVM初探（三）：类加载机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-string%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%B8%8D%E5%8F%AF%E5%8F%98%E6%80%A7"><span class="nav-text">一、String对象的不可变性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1string%E4%B8%BA%E4%BB%80%E4%B9%88%E6%98%AF%E4%B8%8D%E5%8F%AF%E5%8F%98%E7%9A%84"><span class="nav-text">1.String为什么是不可变的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2string%E4%B8%8D%E5%8F%AF%E5%8F%98%E7%9A%84%E5%BF%85%E8%A6%81%E6%80%A7"><span class="nav-text">2.String不可变的必要性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E9%87%8F%E6%B1%A0"><span class="nav-text">二、字符串常量池</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E4%BD%9C%E7%94%A8"><span class="nav-text">1.作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%85%A5%E6%B1%A0%E6%96%B9%E6%B3%95intern"><span class="nav-text">2.入池方法intern()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-string%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA%E6%96%B9%E5%BC%8F"><span class="nav-text">三、String对象的创建方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E4%BD%BF%E7%94%A8%E5%AD%97%E9%9D%A2%E5%80%BC%E5%BD%A2%E5%BC%8F%E5%88%9B%E5%BB%BA"><span class="nav-text">1.使用字面值形式创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E4%BD%BF%E7%94%A8new%E5%85%B3%E9%94%AE%E5%AD%97%E5%88%9B%E5%BB%BA"><span class="nav-text">2.使用new关键字创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E5%B0%8F%E7%BB%93"><span class="nav-text">3.小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-string%E7%9A%84%E6%8B%BC%E6%8E%A5"><span class="nav-text">四、String的拼接</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1stringbuilder"><span class="nav-text">1.StringBuilder</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%8A%A0%E5%8F%B7%E6%8B%BC%E6%8E%A5%E4%B8%8Eappend%E6%96%B9%E6%B3%95%E6%8B%BC%E6%8E%A5"><span class="nav-text">2.加号拼接与append方法拼接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3stringbuffer"><span class="nav-text">3.StringBuffer</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
